<!-- src/views/company/ApplicationManagement.vue -->
<template>
  <div class="application-management">
    <div class="header">
      <h2>岗位申请管理</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索学生姓名或岗位名称"
            clearable
            @clear="resetSearch"
            @keyup.enter="fetchApplications"
          >
            <template #append>
              <el-button icon="Search" @click="fetchApplications" />
            </template>
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-select
            v-model="searchParams.status"
            placeholder="申请状态"
            clearable
            @change="fetchApplications"
          >
            <el-option label="全部" value="" />
            <el-option label="待处理" :value="0" />
            <el-option label="已接受" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 申请列表 -->
    <el-card>
      <el-table
        :data="applications"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="positionTitle" label="申请岗位" min-width="150" />
        <el-table-column prop="appliedAt" label="申请时间" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.appliedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getApplicationStatusType(scope.row.status)">
              {{ getApplicationStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 修改操作列的宽度和按钮布局 -->
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="viewApplicationDetail(scope.row)">查看详情</el-button>
              <el-button
                  v-if="scope.row.status === 0"
                  size="small"
                  type="success"
                  @click="handleApplication(scope.row, 1)"
              >
                接受
              </el-button>
              <el-button
                  v-if="scope.row.status === 0"
                  size="small"
                  type="danger"
                  @click="handleApplication(scope.row, 2)"
              >
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        class="pagination"
      />
    </el-card>

    <!-- 申请详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="700px"
    >
      <div v-if="selectedApplication" class="application-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">{{ selectedApplication.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ selectedApplication.studentId }}</el-descriptions-item>
          <el-descriptions-item label="申请岗位">{{ selectedApplication.positionTitle }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(selectedApplication.appliedAt) }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getApplicationStatusType(selectedApplication.status)">
              {{ getApplicationStatusLabel(selectedApplication.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedApplication.studentPhone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ selectedApplication.studentEmail }}</el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="selectedApplication.processedAt">
            {{ formatDate(selectedApplication.processedAt) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="resume-section" v-if="selectedApplication.resumeUrl">
          <h4>简历附件</h4>
          <el-link :href="selectedApplication.resumeUrl" target="_blank">下载简历</el-link>
        </div>

        <div class="cover-letter-section" v-if="selectedApplication.coverLetter">
          <h4>求职信</h4>
          <p>{{ selectedApplication.coverLetter }}</p>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            v-if="selectedApplication && selectedApplication.status === 0"
            type="success"
            @click="handleApplication(selectedApplication, 1)"
          >
            接受
          </el-button>
          <el-button
            v-if="selectedApplication && selectedApplication.status === 0"
            type="danger"
            @click="handleApplication(selectedApplication, 2)"
          >
            拒绝
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useCompanyStore } from '../../store/company'
import { ElMessage, ElMessageBox } from 'element-plus'

const companyStore = useCompanyStore()

const applications = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedApplication = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取申请列表
const fetchApplications = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize,
      ...searchParams
    }

    const response = await companyStore.fetchApplications(params)
    applications.value = response.content || response
    pagination.total = response.totalElements || 0
  } catch (error) {
    ElMessage.error('获取申请列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.status = ''
  pagination.currentPage = 1
  fetchApplications()
}

// 查看申请详情
const viewApplicationDetail = async (application) => {
  try {
    const detail = await companyStore.fetchApplicationDetail(application.id)
    selectedApplication.value = detail
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取申请详情失败: ' + (error.response?.data?.message || error.message))
  }
}

// 处理申请（接受/拒绝）
// 处理申请（接受/拒绝）
const handleApplication = (application, status) => {
  const action = status === 1 ? '接受' : '拒绝'
  const message = status === 1
      ? `确定要接受学生"${application.studentName}"的申请吗？`
      : `确定要拒绝学生"${application.studentName}"的申请吗？`

  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 确保发送正确的数据格式
      const data = { status: status }
      await companyStore.processApplication(application.id, data)
      ElMessage.success(`${action}成功`)
      detailDialogVisible.value = false
      fetchApplications()
    } catch (error) {
      ElMessage.error(`${action}失败: ` + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 获取申请状态类型
const getApplicationStatusType = (status) => {
  switch (status) {
    case 0: return 'info'    // 待处理
    case 1: return 'success' // 已接受
    case 2: return 'danger'  // 已拒绝
    case 3: return 'warning' // 已取消
    default: return ''
  }
}

// 获取申请状态标签
const getApplicationStatusLabel = (status) => {
  switch (status) {
    case 0: return '待处理'
    case 1: return '已接受'
    case 2: return '已拒绝'
    case 3: return '已取消'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 分页处理
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchApplications()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchApplications()
}

onMounted(() => {
  fetchApplications()
})
</script>

<style scoped>
.application-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.resume-section, .cover-letter-section {
  margin-top: 20px;
}

.cover-letter-section p {
  white-space: pre-wrap;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>
